﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace skald_db
{
    public partial class frmMain : Form
    {
        public db_to_app_layer LAYER = new db_to_app_layer();// current connection init on form creation
        public int top_class_shown_id  ;
        public string top_class_shown_name  ;
        public int top_class_shown_pid ;
        public frmMain()                                     // creator of form started
        {
            // workflow logic
            
            bool close_after_init = true;
            Program.is_connected_to_db = false;

            try
              {
            string pth = System.IO.Directory.GetCurrentDirectory() + @"\cfg\options.ini";
            string[] str = System.IO.File.ReadAllLines(pth);
            Program.global_conn_str = str[0];
            Program.global_db_name = str[1];
            }
            catch(Exception e){
                MessageBox.Show(e.Message);
            }
            bool lol = false;
            if (Program.global_conn_str.Length > 3) lol = true;
            switch (lol) // try load opts
            {
                case true: //optins read norm
                    switch (Program.global_db_name != "") // check db name
                    {
                        case true://all options read
                            if (LAYER.connect( Program.global_conn_str+"Initial catalog= "+Program.global_db_name))//try connect
                            {
                                if (LAYER.db_name == "") // conneted only to server
                                {
                                    if (Program.current_user_role != Program.roles.admin)
                                    {
                                        MessageBox.Show("Т.к. вы не являетесь администратором, то без БД делать нечего!");
                                    }
                                    else
                                    {
                                        Program.global_db_name = "";
                                        MessageBox.Show("Перейдите на вкладку админа и подключите БД");
                                        close_after_init = false;
                                        InitializeComponent();
                                        this.toolStripStatusLabel4.Text = "Отсутствует";
                                    }
                                }
                                else
                                {   // conn to db too

                                    close_after_init = false;
                                    InitializeComponent();
                                    this.toolStripStatusLabel4.Text = LAYER.db_name;
                                    Program.is_connected_to_db = true;


                                }
                            }
                            else //fail connect
                            {
                                MessageBox.Show("Не удалось подключиться к серверу!");
                            
                            }
                            break;
                        case false: // only server
                            if (LAYER.connect(Program.global_conn_str))//try connect
                            {
                                if (Program.current_user_role != Program.roles.admin)
                                {
                                    MessageBox.Show("Т.к. вы не являетесь администратором, то без БД делать нечего!");
                                }
                                else
                                {
                                    Program.global_db_name = "";
                                    MessageBox.Show("Перейдите на вкладку админа и подключите БД");
                                    close_after_init = false;
                                    InitializeComponent();
                                    this.toolStripStatusLabel4.Text = "Отсутствует";
                                }
                            }
                            else //if fail
                            {
                                MessageBox.Show("Не удалось подключиться к серверу!");
                            }
                            break;

                    }

                    break;
                case false:// wrong read
                    MessageBox.Show("Некорректный файл настроек! Проверьте целостность файла");
                    break;

            }

            if (close_after_init)
            {

                Application.Exit();
                return;
            }
           //------------------------------------------------------------ -
            switch (Program.current_user_role)
            {

                case Program.roles.admin:
                    this.toolStripStatusLabel2.Text = "Администратор";
                    break;
                case Program.roles.op:
                    this.toolStripStatusLabel2.Text = "Оператор";
                    break;
                case Program.roles.man:
                    this.toolStripStatusLabel2.Text = "Менеджер";
                    break;

            }
            //==========================================================
            //init user form elements

            foreach(TabPage t in this.tabControl1.TabPages){
                foreach (Control c in t.Controls)
                {
                   if( c.Tag == "dev"){
                        c.Visible = false;
                   }
                }

            }
            if (Program.current_user_role == Program.roles.op) {

                foreach (TabPage t in this.tabControl1.TabPages)
                {
                    foreach (Control c in t.Controls)
                    {
                        if (c.Tag == "man")
                        {
                            c.Visible = false;
                        }
                    }

                }
            }
            if (Program.current_user_role != Program.roles.admin) {
                button4.Visible = false;
                button6.Visible = false;
            }
            Authorisation a = new Authorisation();
            
            this.comboBox2.Items.AddRange(a.GetUsers());
            this.toolStripStatusLabel4.Text = LAYER.db_name;
            get_dbs_to_data_grid(); // collect info from server about db's and put it into admin table
            this.tabControl1.SelectedTab = this.tabPage5;
            this.label8.Text = System.Windows.Forms.Application.ExecutablePath;
            string path = System.IO.Directory.GetCurrentDirectory() + @"\cfg\options.ini";
            this.label9.Text = System.IO.File.Exists(path) ? path : "Не найден";
        }

        private void get_dbs_to_data_grid()
        {


            if(LAYER.select("sys.databases", "name" )){
                this.dataGridView2.Rows.Clear(); //to redraw

                for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
                {
                    string[] l = new string[LAYER.main_data_buffer[0].Length];
                    int i = 0;
                    foreach (object o in LAYER.main_data_buffer[j])
                    {
                        l[i] = Convert.ToString(o);
                        i++;
                    }
                    LAYER.main_data_buffer[j] = l;

                }
                 LAYER.main_data_buffer.RemoveRange(0, 4);
                foreach (Array arr in LAYER.main_data_buffer)
                {
                    this.dataGridView2.Rows.Add(arr.GetValue(0));

                    if (arr.GetValue(0).ToString() == LAYER.db_name) this.dataGridView2.Rows[this.dataGridView2.Rows.Count - 1].Cells[0].Style.BackColor = Color.Cyan;
                }

            } 
        }
        private void button8_Click(object sender, EventArgs e){
            string del = this.dataGridView2.SelectedCells[0].Value.ToString();
            if (Program.is_connected_to_db && LAYER.db_name ==del) {
            }else{
                get_dbs_to_data_grid();
            }
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
        }


        private void button7_Click(object sender, EventArgs e)
        {
            inputbox deploy = new inputbox();
            deploy.Show();
            //deploy.

            if(deploy.DialogResult==DialogResult.OK){
                string dep = deploy.return_db ;
                //foreach(DataGridCell c in dataGridView2.Columns){
                //    if(c.ToString() == dep){break;}
                //}
                LAYER.deploy(dep,deploy.return_length,deploy.return_width,create_db : true);
            }
            get_dbs_to_data_grid();
        }


        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            string[] str = System.IO.File.ReadAllLines(System.IO.Directory.GetCurrentDirectory() + @"\cfg\options.ini");
            str[0] = Program.global_conn_str;
            str[1] = LAYER.db_name;
            System.IO.File.WriteAllLines(System.IO.Directory.GetCurrentDirectory() + @"\cfg\options.ini",str);
            Application.Exit();
        }

        public void put_data_to_class_format() {
            this.dataGridView3.Rows.Clear(); //to redraw

            for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
            {
                string[] l = new string[LAYER.main_data_buffer[0].Length];
                int i = 0;
                foreach (object o in LAYER.main_data_buffer[j])
                {
                    l[i] = Convert.ToString(o);
                    i++;
                }
                LAYER.main_data_buffer[j] = l;

            }

            foreach (Array arr in LAYER.main_data_buffer)
            {
                this.dataGridView3.Rows.Add(arr.GetValue(0), arr.GetValue(1));

                if (arr.GetValue(2).ToString() == "True") this.dataGridView3.Rows[this.dataGridView3.Rows.Count - 1].Cells[1].Style.BackColor = Color.White;
                else
                {
                    this.dataGridView3.Rows[this.dataGridView3.Rows.Count - 1].Cells[1].Style.BackColor = Color.Azure;
                }
            }
            
            
        
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (!LAYER.is_connected) {
                this.tabControl1.SelectedIndex = 1;
                MessageBox.Show("сначала подключиите бд");

                return;
            }
 
            if (e.TabPageIndex == 3) { 
            LAYER.get_class_nodes();
            top_class_shown_id = 0;
            top_class_shown_name = "Верхний уровень классификатора";
            put_data_to_class_format();
            return;
            }
            if (Program.current_user_role != Program.roles.admin && e.Action == TabControlAction.Selected && e.TabPageIndex==0) {
                this.tabControl1.DeselectTab(0);
                MessageBox.Show("Только для администратора !", "Ошибка доступа");
            }
            if (e.TabPageIndex == 6) {
                LAYER.select("class where is_item  = True", "class_name");
        
            
            
            
            }
            if (e.TabPageIndex == 4) {

                LAYER.get_all_records();
                this.dataGridView5.Rows.Clear(); //to redraw

                for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
                {
                    string[] l = new string[LAYER.main_data_buffer[0].Length];
                    int i = 0;
                    foreach (object o in LAYER.main_data_buffer[j])
                    {
                        l[i] = Convert.ToString(o);
                        i++;
                    }
                    LAYER.main_data_buffer[j] = l;

                }
                
                foreach (Array arr in LAYER.main_data_buffer)
                {
                    string[] a = new string[arr.Length];
                    int i = 0;
                    foreach (object o in arr) {
                        a[i] = o.ToString();
                        i++;
                    }

                    this.dataGridView5.Rows.Add(a);

                }
            
            
            }

        }

        private void dataGridView3_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            top_class_shown_pid = top_class_shown_id;
            top_class_shown_id = Convert.ToInt32(this.dataGridView3.Rows[e.RowIndex].Cells[0].Value.ToString());
            if (this.dataGridView3.Rows[e.RowIndex].Cells[1].Style.BackColor == Color.White) { return; }
            if (LAYER.get_class_nodes(top_class_shown_id))
            { }
            else { return; }
            this.dataGridView3.Rows.Clear(); //to redraw

            put_data_to_class_format();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            LAYER.get_class_nodes();
            put_data_to_class_format();
        }
        
        private void button2_Click(object sender, EventArgs e)
        {   dataGridView1.Rows.Clear();
        LAYER.execute_proc(@"use " + LAYER.db_name + @"
 SELECT      [place] /  dbo.get_whs_length()      ,[place] /  dbo.get_whs_width() ,id,		class_name      ,[state]

FROM class,[goods] where name = node_id");
        for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
        {
            string[] l = new string[LAYER.main_data_buffer[0].Length];
            int i = 0;
            foreach (object o in LAYER.main_data_buffer[j])
            {
                l[i] = Convert.ToString(o);
                i++;
            }
            LAYER.main_data_buffer[j] = l;

        }

        foreach (Array arr in LAYER.main_data_buffer)
        {
            string[] a = new string[arr.Length];
            int i = 0;
            foreach (object o in arr)
            {
                a[i] = o.ToString();
                i++;
            }

            this.dataGridView1.Rows.Add(a);

        }
           
        }


        private void button1_Click(object sender, EventArgs e)
        {
             



            {
                string search = "";
                bool check = false;

                if (DialogResult.OK == frmAuth.PromptBox("Поиск по классификатору", "Введите имя позиции", "выводить ссылки оглавления", "", ref check, ref check, 1, ref search))
                {
                    if (LAYER.search_class_name(search, check))
                    {
                        string result = string.Format("Номер позиции {0}\nНазвание {1}\nНаличие {2}\nОписание  {3}\nЯвляется страницей {4}\n");
                        MessageBox.Show(result, "Результаты поиска");
                    }
                    else
                    {
                        MessageBox.Show("Не найдено", "Результаты поиска");
                    }
                }

            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            LAYER.delete_table("history");
            this.dataGridView5.Rows.Clear(); //to redraw

                for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
                {
                    string[] l = new string[LAYER.main_data_buffer[0].Length];
                    int i = 0;
                    foreach (object o in LAYER.main_data_buffer[j])
                    {
                        l[i] = Convert.ToString(o);
                        i++;
                    }
                    LAYER.main_data_buffer[j] = l;

                }
                
                foreach (Array arr in LAYER.main_data_buffer)
                {
                    string[] a = new string[arr.Length];
                    int i = 0;
                    foreach (object o in arr) {
                        a[i] = o.ToString();
                        i++;
                    }

                    this.dataGridView5.Rows.Add(a);

                }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            Authorisation a = new Authorisation();
            a.AddUser(textBox1.Text, textBox2.Text, comboBox1.SelectedIndex+1);
        }

 

        private void button12_Click(object sender, EventArgs e)
        {
            string kool = "";
            string fav = "";
            bool kal = false;
            if (frmAuth.PromptBox("имя позиции", "создание позиции", "лист или узел", "", ref kal, ref kal, 1, ref kool) == DialogResult.OK  &&
                frmAuth.PromptBox("номер отца", "создание позиции", "лист или узел", "", ref kal, ref kal, 0, ref fav) == DialogResult.OK&& fav != "" && kool!="")
            {
                LAYER.insert_class_node(kool, fav,kal) ;
                LAYER.get_class_nodes();
            }

        }

        private void button24_Click(object sender, EventArgs e)
        {
            string dop_info;
            string num;
          
            
            
            
            //layer.do_record_act

        }

        private void button4_Click(object sender, EventArgs e)
        {
            foreach (TabPage t in this.tabControl1.TabPages)
            {
                foreach (Control c in t.Controls)
                {
                    if (c.Tag == "dev")
                    {
                        c.Visible = true;
                    }
                }

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            LAYER.execute_proc(textBox6.Text);
            this.dataGridView7.Rows.Clear();
            try
            {
                this.dataGridView7.ColumnCount = LAYER.main_data_buffer[0].Length;
            }catch(Exception ex){
                return;
            }
            
            for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
            {
                string[] l = new string[LAYER.main_data_buffer[0].Length];
                int i = 0;
                foreach (object o in LAYER.main_data_buffer[j])
                {
                    l[i] = Convert.ToString(o);
                    i++;
                }
                LAYER.main_data_buffer[j] = l;

            }

            foreach (Array arr in LAYER.main_data_buffer)
            {
                string[] a = new string[arr.Length];
                int i = 0;
                foreach (object o in arr)
                {
                    a[i] = o.ToString();
                    i++;
                }

                this.dataGridView7.Rows.Add(a);

            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            Authorisation a = new Authorisation();
            a.DeleteUser(comboBox2.SelectedItem.ToString());
            comboBox2.Items.Clear();
            this.comboBox2.Items.AddRange(a.GetUsers());

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button22_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button23_Click(object sender, EventArgs e)
        {
           LAYER.execute_proc(@"USE "+LAYER.db_name+@" INSERT INTO  [goods]
           ([name]
           ,[state]
           ,[place])
                    VALUES
           (0
           ,456
           ,124)
GO

INSERT INTO [anton].[dbo].[history]
           ( [record_date]
           ,[record_goods_id]
           ,[record_amount]
           ,[record_income_flag]
 )
     VALUES
           ( 
            getdate()
           , (select max(id) from  goods) 
           ,"+234  +@"
           ,1)
 
GO");
 
        }

        private void button13_Click(object sender, EventArgs e)
        {
            this.dataGridView5.Rows.Clear();
            LAYER.select("history");
            for (int j = 0; j < LAYER.main_data_buffer.Count; j++)
            {
                string[] l = new string[LAYER.main_data_buffer[0].Length];
                int i = 0;
                foreach (object o in LAYER.main_data_buffer[j])
                {
                    l[i] = Convert.ToString(o);
                    i++;
                }
                LAYER.main_data_buffer[j] = l;

            }

            foreach (Array arr in LAYER.main_data_buffer)
            {
                string[] a = new string[arr.Length];
                int i = 0;
                foreach (object o in arr)
                {
                    a[i] = o.ToString();
                    i++;
                }

                this.dataGridView5.Rows.Add(a);

            }
        }



        

     
    }
}
 